package com.gancp.common.weatherservice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gancp.domain.vo.WeatherData;
import com.gancp.domain.vo.WeatherInfo;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;


/**
 * Created by GCP on 2018/5/6.
 */
public class WeatherServices {

    private String url = "http://api.help.bj.cn/apis/alarm?id=";

    public void getWeather(String city) throws IOException {
        if (city == null) {
            url = url.concat( "nanchang" );
        } else {
            url = url.concat( city );
        }
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet request = new HttpGet( url );
        HttpResponse response = httpClient.execute( request );
        /**请求发送成功，并得到响应**/
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            /**读取服务器返回过来的json字符串数据**/
            String strResult = EntityUtils.toString( response.getEntity() );
            JSONObject jsonObject = JSONObject.parseObject( strResult );
            WeatherInfo weatherInfo = JSON.parseObject( strResult ).toJavaObject( WeatherInfo.class );
            //  获取json数组
            JSONArray array = jsonObject.getJSONArray( "data" );
            int size = array.size();
            List<WeatherData> list = new ArrayList();
            for (int i = 0; i < size; i++) {
                WeatherData obj = array.getJSONObject( i ).toJavaObject( WeatherData.class );
                list.add( obj );
            }
            weatherInfo.setWeatherDataList( list );
            System.out.println( weatherInfo );
        }
    }

    public static void main(String[] args) throws IOException {
        WeatherServices weatherServices = new WeatherServices();
        weatherServices.getWeather( null );
    }
}
